
package com.lomboardrisk.app.ee_new.web.actions;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.EnumMorpher;
import net.sf.json.util.JSONUtils;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import com.lomboardrisk.app.ee_new.service.FlexiblePageService;
import com.lomboardrisk.app.ee_new.web.AJAXTransferBean;
import com.lomboardrisk.app.ee_new.web.WebGuiResponseUtils;
import com.lomboardrisk.app.ee_new.web.displayItem.JqGridData;
import com.lomboardrisk.app.ee_new.web.displayItem.JqGridItem;
import com.lomboardrisk.app.ee_new.web.displayItem.PrincSearchItem;
import com.lomboardrisk.app.ee_new.web.jsonUtils.DateJsonValueProcessor;
import com.lomboardrisk.app.ee_new.web.jsonUtils.MixBean;
import com.lomboardrisk.app.ee_new.web.jsonUtils.MixJsonValueProcessor;
import com.lomboardrisk.app.ee_new.xsd.schemaSource.AccordionItemType;
import com.lomboardrisk.app.ee_new.xsd.schemaSource.ActionDefinitionType;
import com.lomboardrisk.app.ee_new.xsd.schemaSource.CategoryType;
import com.lomboardrisk.app.ee_new.xsd.schemaSource.DataFilterItemType;
import com.lomboardrisk.app.ee_new.xsd.schemaSource.DataFilterRelationEnumType;
import com.lomboardrisk.app.ee_new.xsd.schemaSource.DataFilterType;
import com.lomboardrisk.app.ee_new.xsd.wrapper.EEPageCfgWrapper;


public class JGridAction extends DispatchAction {
	private FlexiblePageService flexibleService;
	
	public void setFlexibleService(FlexiblePageService flexibleService) {
		this.flexibleService = flexibleService;
	}

	protected ActionForward unspecified(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
	throws Exception {
	
		EEPageCfgWrapper wrapper = flexibleService.getEECustomizedWrapper();
		
		System.out.println("wrapper id = " + wrapper.getId());
		
		wrapper.getJqGridCfg().setUrl("jqGrid/ee_real_world/newData.json");
		
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.registerJsonValueProcessor(java.util.Date.class, new DateJsonValueProcessor("yyyy-MM-dd"));
		jsonConfig.registerJsonValueProcessor(MixBean.class, new MixJsonValueProcessor());
		
		System.out.println(JSONObject.fromObject(wrapper.getJqGridCfg(), jsonConfig));
		
		request.setAttribute("jqCfg", JSONObject.fromObject(wrapper.getJqGridCfg(), jsonConfig));
		request.setAttribute("wrapper", wrapper);
		return mapping.findForward("success");
	}
	
	public ActionForward searchPric(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
	throws Exception {
		
		String term = request.getParameter("term");
		
		List<PrincSearchItem> items = new ArrayList<PrincSearchItem>();
		PrincSearchItem item = null;
		for(int i=0; i<10; i++) {
			item = new PrincSearchItem();
			item.setLabel("ja" + i);
			item.setValue("" + i);
			items.add(item);
		}
		
		WebGuiResponseUtils.sendAJAXBean(response, new AJAXTransferBean(getMessageByKey(request,"message.collateral.flexEE.successful","ajax"), JSONArray.fromObject(items)));
		return null;
	}
	public ActionForward createItem(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
	throws Exception {
		
		long cfgId = Integer.parseInt(request.getParameter("cfgId"));
		String categoryId = request.getParameter("categoryId");
		
		DataFilterType dataFilter = new DataFilterType();
		dataFilter.setId(UUID.randomUUID().toString());
		
		JSONObject jbItem = JSONObject.fromObject(request.getParameter("item"));
		AccordionItemType item = (AccordionItemType) JSONObject.toBean(jbItem, AccordionItemType.class);
		item.setId(UUID.randomUUID().toString());
		item.setDataFilterRef(dataFilter.getId());
		
		long id = flexibleService.createEECategoryItem(cfgId, categoryId, item, dataFilter);
		
		String jsonStr = "{\"id\": " + id + ", \"itemId\": \"" + item.getId() + "\", \"dataFilterId\": \"" + dataFilter.getId() + "\"}";
		WebGuiResponseUtils.sendAJAXBean(response, new AJAXTransferBean(getMessageByKey(request,"message.collateral.flexEE.successful","ajax"), jsonStr));
		return null;
	}
	
	public ActionForward updateItem(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
	throws Exception {
		
		HttpSession session = request.getSession(false);
		System.out.println(session.getId());
		
		long cfgId = Integer.parseInt(request.getParameter("cfgId"));
		JSONObject jbItem = JSONObject.fromObject(request.getParameter("item"));
		AccordionItemType item = (AccordionItemType) JSONObject.toBean(jbItem, AccordionItemType.class);
		
		long id = flexibleService.modifyEECategoryItem(cfgId, item);
		
		WebGuiResponseUtils.sendAJAXBean(response, new AJAXTransferBean(getMessageByKey(request,"message.collateral.flexEE.successful","ajax"), id));

		return null;
	}
	
	public ActionForward updateItemPos(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
	throws Exception {
		
		long cfgId = Integer.parseInt(request.getParameter("cfgId"));
		JSONArray jbItem = JSONArray.fromObject(request.getParameter("idsArray"));
		
		String[][] idArrs = (String[][]) JSONArray.toArray(jbItem, String.class);
		
		long id = flexibleService.modifyEECateoryItemPos(cfgId, idArrs);
		
		WebGuiResponseUtils.sendAJAXBean(response, new AJAXTransferBean(getMessageByKey(request,"message.collateral.flexEE.successful","ajax"), id));
		return null;
	}
	
	public ActionForward delItem(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
	throws Exception {
		
		long cfgId = Integer.parseInt(request.getParameter("cfgId"));
		String categoryId = request.getParameter("categoryId");
		String itemId = request.getParameter("itemId");
		
		long id = flexibleService.removeEECategoryItem(cfgId, categoryId, itemId);
		
		WebGuiResponseUtils.sendAJAXBean(response, new AJAXTransferBean(getMessageByKey(request,"message.collateral.flexEE.successful","ajax"), id));
		return null;
	}
	
	public ActionForward createCatagory(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
	throws Exception {
		
		long cfgId = Integer.parseInt(request.getParameter("cfgId"));
		JSONObject jbItem = JSONObject.fromObject(request.getParameter("item"));
		CategoryType category = (CategoryType) JSONObject.toBean(jbItem, CategoryType.class);
		category.setId(UUID.randomUUID().toString());
		
		long id = flexibleService.createEECategory(cfgId, category);
		
		WebGuiResponseUtils.sendAJAXBean(response, new AJAXTransferBean(getMessageByKey(request,"message.collateral.flexEE.successful","ajax"), id));
		return null;
	}
	
	public ActionForward updateCatagory(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
	throws Exception {
		
		long cfgId = Integer.parseInt(request.getParameter("cfgId"));
		JSONObject jbItem = JSONObject.fromObject(request.getParameter("category"));
		CategoryType item = (CategoryType) JSONObject.toBean(jbItem, CategoryType.class);
		
		long id = flexibleService.modifyEECategory(cfgId, item);
		
		WebGuiResponseUtils.sendAJAXBean(response, new AJAXTransferBean(getMessageByKey(request,"message.collateral.flexEE.successful","ajax"), id));
		return null;
	}
	
	public ActionForward delCatagory(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
	throws Exception {
		
		long cfgId = Integer.parseInt(request.getParameter("cfgId"));
		String categoryId = request.getParameter("categoryId");
		
		long id = flexibleService.removeEECategory(cfgId, categoryId);
		
		WebGuiResponseUtils.sendAJAXBean(response, new AJAXTransferBean(getMessageByKey(request,"message.collateral.flexEE.successful","ajax"), id));
		return null;
	}
	
	public ActionForward updateGridPro(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
	throws Exception {
		
		long cfgId = Integer.parseInt(request.getParameter("cfgId"));
		
		String hiddenIdStr = request.getParameter("hiddenIds");
		String[] hiddenIds = null;
		if(hiddenIdStr != null) {
			JSONArray jbHiddenCols = JSONArray.fromObject(hiddenIdStr);
			hiddenIds = (String[]) JSONArray.toArray(jbHiddenCols, String.class);
		}
		
		String permStr = request.getParameter("perm");
		Integer[] perm = null;
		if(permStr != null) {
			JSONArray jbOrders = JSONArray.fromObject(permStr);
			perm = (Integer[]) JSONArray.toArray(jbOrders, Integer.class);
		}
		
		long id = flexibleService.modifyEEDataGridPro(cfgId, hiddenIds, perm);
		
		WebGuiResponseUtils.sendAJAXBean(response, new AJAXTransferBean(getMessageByKey(request,"message.collateral.flexEE.successful","ajax"), id));
		return null;
	}
	
	public ActionForward updateDataFilter(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
	throws Exception {
		
		long cfgId = Integer.parseInt(request.getParameter("cfgId"));
		
		
		JSONUtils.getMorpherRegistry().registerMorpher( new EnumMorpher( DataFilterRelationEnumType.class ) );
		JSONArray jbItem = JSONArray.fromObject(request.getParameter("filter"));
		
		Map classMap = new HashMap();
		classMap.put("filterType", DataFilterRelationEnumType.class);
		
		DataFilterItemType[] filterItems = (DataFilterItemType[])JSONArray.toArray(jbItem, DataFilterItemType.class);
		
		String filterId = request.getParameter("filterId");
		
		DataFilterType filter = new DataFilterType();
		filter.setId(filterId);
		
		filter.getDataFilterItem().addAll(Arrays.asList(filterItems));
		
		long id = flexibleService.modifyEEDataFilter(cfgId, filter);
		
		WebGuiResponseUtils.sendAJAXBean(response, new AJAXTransferBean(getMessageByKey(request,"message.collateral.flexEE.successful","ajax"), id));
		return null;
	}
	

	public ActionForward getCallStatus(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
	throws Exception {
		System.out.println("getCallStatus");
		
		StringBuilder builder = new StringBuilder();
		
		builder.append("<select><option value='1'>One</option><option value='2'>Two</option></select>");
		
		WebGuiResponseUtils.sendAJAXBean(response, new AJAXTransferBean(getMessageByKey(request,"message.collateral.flexEE.successful","ajax"), builder.toString()));

		
		return null;
	}
	public ActionForward showActionBtn(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
	throws Exception {
		
		String actionNumStr = request.getParameter("selectedItemNum");
		int actionNum = 0;
		if(actionNumStr != null) {
			actionNum = Integer.parseInt(actionNumStr);
		}
		
		StringBuilder nameBuilder = new StringBuilder();
		
		EEPageCfgWrapper wrapper = flexibleService.getEECustomizedWrapper();
		
		List<ActionDefinitionType> btnList = wrapper.getActionBtns();
		for (int i = 0; i < btnList.size(); i++) {
			ActionDefinitionType cfg = btnList.get(i);
			if (actionNum == 1) {
//				if (!cfg.isMultipleDisplay()) {
				nameBuilder.append(cfg.getIcon()).append(",");
//				}
			} else if (actionNum > 1) {
				if (cfg.isIsMultipleDisplay()) {
					nameBuilder.append(cfg.getIcon()).append(",");
				}
			} else {
			}
		}
		
		if(nameBuilder.length() > 0 && ',' == nameBuilder.charAt(nameBuilder.length()-1)) {
			nameBuilder.deleteCharAt(nameBuilder.length()-1);
		}
		
		WebGuiResponseUtils.sendAJAXBean(response, new AJAXTransferBean(getMessageByKey(request,"message.collateral.flexEE.successful","ajax"), nameBuilder));
		return null;
	}
	
	public ActionForward ccyConvertor(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
	throws Exception {
		StringBuilder errMsg = new StringBuilder();
        
        long originalCurrency = Long.parseLong(request.getParameter("originalCurrency"));
		long resultCurrency =  Long.parseLong(request.getParameter("resultCurrency"));
		double originalAmount = Double.parseDouble(request.getParameter("originalAmount"));

		
		if(errMsg.length() != 0) {
			response.getWriter().print(errMsg);
		} else {
			double rate = 2;
			double resultAmount =originalAmount * rate;
 			response.getWriter().print(resultAmount);
		}
		
		return null;
		
	}
	
	//save comments
	public ActionForward saveComments(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
	throws Exception {
		String savedType = request.getParameter("savedType");
		String eeComments = request.getParameter("eeComments");
		long workflowId = Long.parseLong(request.getParameter("workflowId"));
//		ExtExpServiceRemote eeSvc = CollateralBeanFactory.createExtExpService();
//		eeSvc.setExtExpComment(workflowId, eeComments, savedType);
		
		return null;
	}
	
	//get HTML ELEM
	public ActionForward getHTML(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
	throws Exception {
		
		System.out.println("get HMTL start");
		
		return mapping.findForward("success");
	}
	//get HTML ELEM
	public ActionForward getHTMLNext(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
	throws Exception {

		System.out.println("get HMTL next start");
		
		return mapping.findForward("next");
	}
	
	public ActionForward list(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		
		long page = Long.parseLong(request.getParameter("page"));
		long pageSize = Long.parseLong(request.getParameter("rows"));
		
		List<JqGridItem> items = new ArrayList<JqGridItem>();
		JqGridItem item;
		for(int i=0; i<100; i++) {
			item = new JqGridItem();
			items.add(item);
		}
		
        long totalrecords = 0;
        JqGridData data = new JqGridData();
		data.setItems(items);
		data.setTotal(totalrecords/pageSize);
		data.setPage(page);
		data.setRecords(totalrecords);
		JsonConfig jsonConfig = new JsonConfig();
//		jsonConfig.registerJsonValueProcessor(java.util.Date.class, new JsDateJsonValueProcessor());
		jsonConfig.registerJsonValueProcessor(java.util.Date.class, new DateJsonValueProcessor("yyyy-MM-dd"));
		
		JSONObject result = JSONObject.fromObject(data, jsonConfig);
		WebGuiResponseUtils.sendAJAXBean(response, new AJAXTransferBean(getMessageByKey(request,"message.collateral.flexEE.successful","ajax"), result));

		return null;
	}

	private String getMessageByKey(HttpServletRequest request,String key,String param) {
//		return getResources(request).getMessage(key, param);
		return getResources(request).getMessage(getLocale(request), key, param);
	}
	
}
